let Parser = require('rss-parser');
let parser = new Parser();
import { insertAnimation, findAnimationByGuid, release } from './db'
 
(async () => {
 
  let feed = await parser.parseURL('https://share.dmhy.org/topics/rss/rss.xml');
  console.log(feed.title);
 

  let preg = /magnet:\?xt=urn:btih:\w+/
  await Promise.all(feed.items.reverse().map(async (item: any) => {
    const magnetMatch = item.enclosure.url.match(preg)
    const data = {
      title: item.title,
      link: item.link,
      pubDate: new Date(item.pubDate),
      author: item.author,
      magnet: magnetMatch ? magnetMatch[0] : '',
      content: '',
      guid: item.guid,
      categories: item.categories.map((x: any) => x._).join(','),
    }
    
    const res = await findAnimationByGuid(data.guid)
    if(res.results.length === 0){
      try{
        return await insertAnimation(data)
      }catch(e){
        console.log(e)
      }
    }
    // console.log(item.title + ':' + item.link)
  }))
  await release()
 
})();